<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>stream</title>
    <!-- 引入 Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        img{max-width: 650px;}
    </style>
</head>
<body class="container">
<h1>Stream</h1>
<div class="well">
    <p class="text-danger">Stream是一个抽象接口，其中http的request、stdout实现了此接口</p>
    <div class="text-info">
        Stream的类型：
        <div class="well">
            <p>Readable:可读操作</p>
            <p>Writeable:可写操作</p>
            <p>Duplex：可读、可写操作</p>
            <p>Transform：操作被写入数据，然后读出结果</p>
        </div>
    </div>
    <p class="text-success">
        Stream是EventEmitter实例，Stream事件：
        <div class="well">
            <p>data:当有数据读取时</p>
            <p>end:当没有更多数据读取时</p>
            <p>error:当读、写数据出错时</p>
            <p>finish:所有数据被写入到底层时</p>
        </div>
    </p>
</div>
<h3>创建一个可读流：</h3>
<div class="well">
    <xmp>
var fs=require('fs');
var data='';
//创建可读流
var readStream=fs.createReadStream('readStream.js');
//设置字符编码
readStream.setEncoding('utf-8');
//处理data事件
readStream.on('data',function (chunk) {
data+=chunk;
});
//处理end事件
readStream.on('end',function () {
console.log(data);
})
//处理error事件
readStream.on('error',function (err) {
console.log(err.stack);
});
//处理finish事件
readStream.on('finish',function () {
console.log("&finish^");
})
console.log("程序执行完毕");
    </xmp>
</div>
<h3>创建一个输出流</h3>
<div class="well">
    <xmp>
var fs=require('fs');
//创建一个写入流，并把数据写入out.txt
var writeStream=fs.createWriteStream('out.txt');
//以utf-8格式写入数据
writeStream.write('菜鸟教程','utf-8');
//标记文件末尾
writeStream.end();
//处理流事件：finish
writeStream.on('finish',function () {
console.log('数据写入完成！');
});
//处理流事件：error
writeStream.on('error',function (err) {
console.log('数据处理失败'+err.stack);
});
console.log("程序执行完毕");
    </xmp>
</div>
<h3>管道流</h3>
<div class="well">
    <xmp>
var fs=require('fs');
var readStream=fs.createReadStream('pipeStream.js');
var writeStream=fs.createWriteStream('out.txt');
readStream.pipe(writeStream);
console.log('操作完成！');
    </xmp>
</div>
<h3>链式流：压缩文件</h3>
<div class="well">
    <xmp>
var fs=require('fs');
var zlib=require('zlib');
fs.createReadStream('out.txt').pipe(
zlib.createGzip()
).pipe(
fs.createWriteStream('out.txt.gz')
);
    </xmp>
</div>
<h3>链式流：解压文件</h3>
<div class="well">
    <xmp>
var fs = require("fs");
var zlib = require('zlib');
// 解压 input.txt.gz 文件为 input.txt
fs.createReadStream('out.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("文件解压完成。");
    </xmp>
</div>
</body>
</html>